package initialized

import (
	"fmt"
	"strconv"

	"github.com/hashicorp/consul/api"

	"user/public"
)

func Init_Consul() {

	consulcfg := api.DefaultConfig()

	consulcfg.Address = fmt.Sprintf("%s:%d", public.UserConfig.Consul.Host, public.UserConfig.Consul.Port)

	consulclient, err := api.NewClient(consulcfg)

	if err != nil {
		fmt.Println("Error creating consul client", err)
		return
	}
	//实例化注册信息
	registerInfo := new(api.AgentServiceRegistration)

	registerPort := strconv.Itoa(int(public.UserConfig.Server.Port))
	registerInfo.Address = fmt.Sprintf("%s:%d", public.UserConfig.Server.Host)
	registerInfo.Port = int(public.UserConfig.Server.Port)
	registerInfo.ID = public.UserConfig.Name + registerPort
	registerInfo.Name = public.UserConfig.Name
	registerInfo.Tags = []string{"wsyx", "server", "rpc", "go"}

	//注册到consul里
	err = consulclient.Agent().ServiceRegister(registerInfo)
	if err != nil {
		fmt.Println("Error Register Consul Agent ", err)
		return
	}

}
